package com.bigegg.employee.service.impl;


import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.MessageUtils;
import com.bigegg.employee.domain.TokenWrap;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 当前工程适用于 小程序的登录服务类
 * @author sun
 *
 */
@Service
public class CLoginService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    CUserService cUserService;


    /**
     * 用户名 密码 登录
     * 此方法为类 SysLoginService中方法 login(String username, String password, String code, String uuid) 简化版本
     * 去掉了验证码的验证过程
     * 返回内容进行了相应的包装
     *
     * @param username 用户名
     * @param password 密码
     * @return TokenWrap
     */
    public TokenWrap login(String username, String password) {
        // ---复制代码开始-----------------------
        // 下面内容为复制 SysLoginService中方法 login(String username, String password, String code, String uuid) 内容
        // 用户验证
        Authentication authentication;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // ---复制代码结束-----------------------

        // 对token进行包装
        return wrapToken(loginUser);
    }


    private TokenWrap wrapToken(LoginUser user) {
        TokenWrap tokenWrap = new TokenWrap();
        // 设置用户ID
        tokenWrap.setUid(user.getUser().getUserId());
        List<SysRole> roles = user.getUser().getRoles();
        // 角色判断
        if (roles == null || roles.size() < 1) {
            throw new BadCredentialsException("用户 [ " + user.getUsername() + " ] 身份不符，请管理员对用户进行授权。");
        }
        int typeCode = cUserService.getUserTypeCode(user);

        // 无用户type 代码抛出异常 标识用户无身份
        if (typeCode < 0) {
            throw new BadCredentialsException("用户 [ " + user.getUsername() + " ] 身份不符，请管理员对用户进行授权。");
        }
        tokenWrap.setType(typeCode);
        // 生成token
        String token = tokenService.createToken(user);
        // 设置token
        tokenWrap.setToken(token);
        return tokenWrap;
    }

}
